package craky.keeper.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import craky.keeper.client.R;
import craky.keeper.util.KeeperUtil;

public class ListFooter extends RelativeLayout implements View.OnClickListener
{
    private ImageView footerImage;

    private TextView footerText;

    private KeeperListView listView;

    private boolean hasMoreData;

    public ListFooter(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        this.setOnClickListener(this);
        this.post(new Runnable()
        {
            public void run()
            {
                footerImage = (ImageView)getChildAt(0);
                footerText = (TextView)getChildAt(1);
            }
        });
        this.hasMoreData = true;
    }

    public void loadFinished(boolean hasMoreData)
    {
        this.hasMoreData = hasMoreData;
        footerImage.clearAnimation();
        footerImage.setImageResource(R.drawable.load_more);
        footerImage.setVisibility(hasMoreData? View.VISIBLE: View.GONE);
        footerText.setText(hasMoreData? R.string.load_more: R.string.no_more);
        resetEnabled();
    }

    public void resetEnabled()
    {
        this.setEnabled(hasMoreData);
    }

    private void startLoading()
    {
        this.setEnabled(false);
        footerImage.setImageResource(R.drawable.loading_more);
        footerText.setText(R.string.loading_more);
        float pivot = footerImage.getWidth() / 2.0f;
        Animation animation = new RotateAnimation(0, Integer.MAX_VALUE / 8.0f, pivot, pivot);
        animation.setInterpolator(KeeperUtil.LINEAR_INTERPOLATOR);
        animation.setDuration(Integer.MAX_VALUE);
        this.setVisibility(View.VISIBLE);
        footerImage.startAnimation(animation);
    }

    @Override
    public void onClick(View view)
    {
        if(this.isEnabled())
        {
            if(listView == null)
            {
                listView = (KeeperListView)getParent();
            }

            startLoading();
            listView.loadMore();
        }
    }
}